package com.sqly.doc.menu.qianyue;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.cazaea.sweetalert.SweetAlertDialog;
import com.ihidea.multilinechooselib.MultiLineChooseLayout;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.sqly.doc.R;
import com.sqly.doc.adapter.CommonAdapter;
import com.sqly.doc.adapter.ViewHolder;
import com.sqly.doc.base.MyBaseActivity;
import com.sqly.doc.pojo.JuMin;
import com.sqly.doc.pojo.ServicePackage;
import com.sqly.doc.pojo.SignUp;
import com.sqly.doc.pojo.Team;
import com.sqly.doc.pojo.TeamMember;
import com.sqly.doc.user.choose_user;
import com.sqly.doc.util.CreateBitmap;
import com.sqly.doc.util.HttpUrl;
import com.sqly.doc.util.LvHeightUtil;
import com.sqly.doc.util.MyToastUtil;
import com.sqly.doc.util.NetWorkUtils;
import com.sqly.doc.util.SharedPreferencesUtils;
import com.sqly.doc.util.UserClient;
import com.sqly.doc.util.WriteActivity;
import com.sqly.doc.view.StringUtils;
import com.zyao89.view.zloading.ZLoadingDialog;
import com.zyao89.view.zloading.Z_TYPE;

import org.litepal.crud.DataSupport;

import java.io.File;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cz.msebera.android.httpclient.Header;

//import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * Created by Administrator on 2017-12-05.
 */

public class qianyue_add_bak extends MyBaseActivity {
    //标题
    TextView title, uname;
    /////////////////////////////////甲方内容////////////////////////////////
    TextView qyjg, qysj, fwtd, zgys;
    ListView listView;//团队列表
    EditText lxdh, jmlxdh;
    Spinner qynx;
    private List<String> qynxdata = new ArrayList<>();
    /////////////////////////////////////乙方内容////////////////////////////////
    TextView jmxm, jtzz;
    MultiLineChooseLayout fwb;//服务包内容
    private List<String> fwbdata = new ArrayList<>();
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    List<TeamMember> tmlist;//医疗团队成员
    Team myteam;
    SignUp obj;
    JuMin j;
    Context con = qianyue_add_bak.this;
    ZLoadingDialog dialog;
    ImageView brqm;
    String brqmpic = "";

    @Override
    protected void initUI() {
        setContentView(R.layout.qianyue_add);
        j = (JuMin) getIntent().getExtras().getSerializable("juMin");
        brqm = (ImageView) findViewById(R.id.qm);
        brqm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(con, WriteActivity.class).putExtra("class","ycf_1.class"), 9);
            }
        });
        dialog = new ZLoadingDialog(con);
        dialog.setLoadingBuilder(Z_TYPE.DOUBLE_CIRCLE)//设置类型
                .setLoadingColor(Color.parseColor("#1C86EE"))//颜色
                .setHintText("Loading...")
                .setHintTextSize(16) // 设置字体大小 dp
                .setHintTextColor(Color.parseColor("#1C86EE"));  // 设置字体颜色
//标题
        title = (TextView) findViewById(R.id.title);
        uname = (TextView) findViewById(R.id.uname);
        title.setText("签约");
        uname.setText("保存");
        uname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (fwb.getAllItemSelectedIndex().size() == 0) {
                    new SweetAlertDialog(con, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("提示")
                            .setContentText("请选择服务内容")
                            .show();
                } else if (myteam == null ) {
                    new SweetAlertDialog(con, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("提示")
                            .setContentText("团队信息不全，请联系管理员！")
                            .show();
                } else if( j == null){
                    new SweetAlertDialog(con, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("提示")
                            .setContentText("请选择签约居民！")
                            .show();
                }else {
                    if (brqmpic.equals("")) {
                        new SweetAlertDialog(con, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("提示")
                                .setContentText("签名不能为空")
                                .show();
                    } else {
                        obj.setTbtime(qysj.getText().toString());
                        System.out.println("hhhhhhhhhhhhhhhhhhhhhhh===================="+SharedPreferencesUtils.getParam(con, "uid", "").toString());
                        obj.setParty_a_contractor_id(SharedPreferencesUtils.getParam(con, "uid", "").toString());
                        obj.setParty_a_contractor_name(SharedPreferencesUtils.getParam(con, "uname", "").toString());
                        obj.setParty_a_team_id(myteam.getTid());
                        obj.setParty_a_team_name(myteam.getName());
                        obj.setParty_a_tel(lxdh.getText().toString());
                        obj.setParty_b_tel(jmlxdh.getText().toString());
                        obj.setParty_b_addr(jtzz.getText().toString());
                        obj.setParty_b_id(j.getJKDAH());
                        obj.setParty_b_name(j.getXINGMING());
                        List<ServicePackage> slist = DataSupport.findAll(ServicePackage.class);
                        ArrayList<Integer> fwblist = fwb.getAllItemSelectedIndex();
                        String fwbs = "";
                        for (int i = 0; i < fwblist.size(); i++) {
                            if (i == 0)
                                fwbs = "," + slist.get(fwblist.get(i)).getSid();
                            else
                                fwbs = fwbs + "," + slist.get(fwblist.get(i)).getSid();
                        }
                        obj.setService_pack_id(fwbs);
                        if (NetWorkUtils.isNetworkConnected(con)) {
                            RequestParams ps = new RequestParams();
                            ps.add("type", "2");
                            ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
                            ps.add("entity.contract_age", obj.getContract_age());
                            ps.add("entity.party_a_contractor_id", obj.getParty_a_contractor_id());
                            ps.add("entity.party_a_contractor_name", obj.getParty_a_contractor_name());
                            ps.add("entity.party_a_team_id", obj.getParty_a_team_id());
                            ps.add("entity.party_a_team_name", obj.getParty_a_team_name());
                            ps.add("entity.party_a_tel", obj.getParty_a_tel());
                            ps.add("entity.party_b_tel", obj.getParty_b_tel());
                            ps.add("entity.party_b_addr", obj.getParty_b_addr());
                            ps.add("entity.party_b_id", obj.getParty_b_id());
                            ps.add("entity.party_b_name", obj.getParty_b_name());
                            ps.add("entity.tbtime", obj.getTbtime());
                            ps.add("service_pack_id", obj.getService_pack_id());
                            try {
                                ps.put("img", new File(Environment.getExternalStorageDirectory() + "/" + brqmpic + ".jpg"));
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }
                            UserClient.get(HttpUrl.SignAdd, ps, new AsyncHttpResponseHandler() {
                                @Override
                                public void onStart() {
                                    super.onStart();
                                    dialog.show();
                                }

                                @Override
                                public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                                    String content = new String(response);
                                    dialog.dismiss();
                                    List<SignUp> jlist = DataSupport.where("party_a_contractor_id = ? and party_b_id=?", SharedPreferencesUtils.getParam(con, "uid", "").toString(), j.getJKDAH()).find(SignUp.class);
                                    if (jlist.size() > 0) {
                                        obj.setIsupdate("1");
                                        obj.setQm(brqmpic);
                                        obj.update(obj.getId());
                                        j.setIssign("2");
                                        j.update(j.getId());
                                        MyToastUtil.ShowToast(con, "保存成功");
                                        finish();
                                    } else {
                                        obj.setIsupdate("1");
                                        obj.setQm(brqmpic);
                                        obj.save();
                                        j.setIssign("2");
                                        j.update(j.getId());
                                        MyToastUtil.ShowToast(con, "保存成功");
                                        finish();
                                    }
                                }

                                @Override
                                public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {

                                    dialog.dismiss();
                                }
                            });
                        } else {
                            List<SignUp> jlist = DataSupport.where("party_a_contractor_id = ? and party_b_id=?", SharedPreferencesUtils.getParam(con, "uid", "").toString(), j.getJKDAH()).find(SignUp.class);
                            if (jlist.size() > 0) {
                                obj.setIsupdate("2");
                                obj.setQm(brqmpic);
                                obj.update(obj.getId());
                                List<SignUp> ddd = DataSupport.where("party_a_contractor_id = ? and party_b_id=?", SharedPreferencesUtils.getParam(con, "uid", "").toString(), j.getJKDAH()).find(SignUp.class);
                                System.out.println("本地保存" + ddd.size());
                                j.setIssign("2");
                                j.update(j.getId());
                                MyToastUtil.ShowToast(con, "保存本地成功");
                                finish();
                            } else {
                                obj.setIsupdate("2");
                                obj.setQm(brqmpic);
                                obj.save();
                                List<SignUp> dd = DataSupport.where("party_a_contractor_id = ? and party_b_id=?", SharedPreferencesUtils.getParam(con, "uid", "").toString(), j.getJKDAH()).find(SignUp.class);
                                System.out.println("本地保存" + dd.size());
                                j.setIssign("2");
                                j.update(j.getId());
                                MyToastUtil.ShowToast(con, "保存本地成功");
                                finish();
                            }

                        }

                    }
                }
            }
        });
        qyjg = (TextView) findViewById(R.id.qyjg);
        qysj = (TextView) findViewById(R.id.qysj);
        qysj.setText(df.format(new Date()));
        fwtd = (TextView) findViewById(R.id.fwtd);
        zgys = (TextView) findViewById(R.id.zgys);
        lxdh = (EditText) findViewById(R.id.lxdh);
        jmlxdh = (EditText) findViewById(R.id.jmlxdh);

        zgys.setText(SharedPreferencesUtils.getParam(con, "uname", "").toString());
        lxdh.setText(SharedPreferencesUtils.getParam(con, "phone", "").toString());
        jmxm = (TextView) findViewById(R.id.jmxm);
        if (j != null && !StringUtils.isEmpty(j.getXINGMING()))
            jmxm.setText(j.getXINGMING());
        if (j != null && !StringUtils.isEmpty(j.getLXDH()))
            jmlxdh.setText(j.getLXDH());
        jtzz = (TextView) findViewById(R.id.jtzz);
        if (j != null && !StringUtils.isEmpty(j.getCZDZ()))
            jtzz.setText(j.getCZDZ());

        qynx = (Spinner) findViewById(R.id.qynx);
        fwb = (MultiLineChooseLayout) findViewById(R.id.fwnr);
        listView = (ListView) findViewById(R.id.listView);


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {

        } else {

            if (requestCode == 9) {

                byte[] bis = data.getByteArrayExtra("bitmap");
                Bitmap bmp = BitmapFactory.decodeByteArray(bis, 0, bis.length);
                Bitmap bb = CreateBitmap.zoomImg(bmp, 1, 1);
                brqm.setImageBitmap(bb);
                brqmpic = CreateBitmap.saveMyBitmap(bb);
            }
            if (requestCode == 1) {
                j = (JuMin) data.getExtras().getSerializable("juMin");
                jmxm.setText(j.getXINGMING());
                jtzz.setText(j.getHJDZ());
                List<SignUp> jlist = DataSupport.where("party_a_contractor_id = ? and party_b_id=?", SharedPreferencesUtils.getParam(con, "uid", "").toString(), j.getJKDAH()).find(SignUp.class);
                fwb.cancelAllSelectedItems();
                brqm.setImageResource(R.mipmap.qm);
                brqmpic = "";
                jmlxdh.setText(StringUtils.isEmpty(j.getLXDH()) ? "" : j.getLXDH());
                if (jlist.size() > 0) {
                    Log.i("签约信息", jlist.size() + "" + jlist.get(0).getService_pack_id());
                    obj = jlist.get(0);
                    if (obj != null && !StringUtils.isEmpty(obj.getQm())) {
                        brqmpic = obj.getQm();
                        brqm.setImageBitmap(BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/" + brqmpic + ".jpg"));
                    }
                    List<ServicePackage> sl = DataSupport.findAll(ServicePackage.class);
                    String[] serviceid = jlist.get(0).getService_pack_id().split(",");
                    for (int i = 0; i < serviceid.length; i++) {
                        for (int j = 0; j < sl.size(); j++) {
                            if (serviceid[i].equals(sl.get(j).getSid()))
                                fwb.setIndexItemSelected(j);
                        }
                    }
                } else {
                    obj = new SignUp();
                    fwb.cancelAllSelectedItems();
                    brqm.setImageResource(R.mipmap.qm);
                    brqmpic = "";
                }
            }
        }
    }

    @Override
    protected void initData() {
        obj = new SignUp();
        obj.setContract_age("1");
        //团队成员
        tmlist = DataSupport.where("team_id=? and isdel=0", SharedPreferencesUtils.getParam(con, "teamid", "").toString()).find(TeamMember.class);
        listView.setAdapter(new CommonAdapter<TeamMember>(con, tmlist, R.layout.qy_team_item) {
            @Override
            public void convert(ViewHolder helper, TeamMember item) {
                helper.setText(R.id.name, item.getMember_name());
                helper.setText(R.id.tdmc, item.getName());
                helper.setText(R.id.jgmc, item.getNameD());
            }
        });
        LvHeightUtil.setListViewHeightBasedOnChildren(listView);
        //填充我的团队信息
        List<Team> l = DataSupport.where("tid=?", SharedPreferencesUtils.getParam(con, "teamid", "").toString()).find(Team.class);
        if (l.size() > 0) {
            myteam = l.get(0);
            qyjg.setText(myteam.getNameD());
            fwtd.setText(myteam.getName());

        } else {
            new SweetAlertDialog(con, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("提示")
                    .setContentText("团队信息不存在。。。")
                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            finish();
                        }
                    })
                    .show();
            myteam = null;
        }
        ///签约年限
        qynxdata.add("1");
        qynxdata.add("2");
        qynxdata.add("3");
        qynx.setAdapter(new CommonAdapter<String>(con, qynxdata, R.layout.sp_item) {
            @Override
            public void convert(ViewHolder helper, String item) {
                helper.setText(R.id.name, item);
            }
        });
        qynx.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                obj.setContract_age((position + 1) + "");
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


        List<ServicePackage> list = DataSupport.findAll(ServicePackage.class);
        for (int i = 0; i < list.size(); i++) {
            fwbdata.add(list.get(i).getName());
        }
        fwb.setList(fwbdata);
        if (j != null) {
            List<SignUp> jlist = DataSupport.where("party_a_contractor_id = ? and party_b_id=?", SharedPreferencesUtils.getParam(con, "uid", "").toString(), j.getJKDAH()).find(SignUp.class);

            if (jlist.size() > 0) {
                Log.i("签约信息", jlist.size() + "" + jlist.get(0).getService_pack_id());
                obj = jlist.get(0);
                if (obj != null && !StringUtils.isEmpty(obj.getQm())) {
                    brqmpic = obj.getQm();
                    brqm.setImageBitmap(BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/" + brqmpic + ".jpg"));
                }
                List<ServicePackage> sl = DataSupport.findAll(ServicePackage.class);
                String[] serviceid = jlist.get(0).getService_pack_id().split(",");
                for (int i = 0; i < serviceid.length; i++) {
                    for (int j = 0; j < sl.size(); j++) {
                        if (serviceid[i].equals(sl.get(j).getSid()))
                            fwb.setIndexItemSelected(j);
                    }
                }

            }
        }
    }

    @Override
    protected void initListener() {

        jmxm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(con, choose_user.class).putExtra("cname", "qianyue_add.class").putExtra("type", "wqy"), 1);
            }
        });

    }
}
